package com.itheima.app.service.impl;


import cn.hutool.core.bean.BeanUtil;
import com.itheima.app.mapper.OrderMapper;
import com.itheima.app.service.OrderService;
import com.itheima.health.model.dtos.OrderDto;
import com.itheima.health.model.pojos.Member1;
import com.itheima.health.model.pojos.Order;
import com.itheima.health.model.pojos.OrderSetting;
import com.itheima.health.model.vos.OrderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.Date;


@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Override
    public Integer OrderDto(OrderDto dto) {
        //体检预约方法处理逻辑比较复杂，需要进行如下业务处理：
        //1、检查用户所选择的预约日期是否已经提前进行了预约设置，如果没有设置则无法进行
        OrderSetting orderSetting = orderMapper.selectByOrderDate(dto.getOrderDate());
        if(orderSetting == null){
            throw new RuntimeException("所选日期没有进行预约设置，请确认");
        }
       // 2、检查用户所选择的预约日期是否已经约满，如果已经约满则无法预约

        if(orderSetting.getReservations() >= orderSetting.getNumber()){
            throw new RuntimeException("所选日期预约已满，请选择其他日期");
        }
        //3、检查用户是否重复预约（同一个用户在同一天预约了同一个套餐），如果是重复预约  则无法完成再次预约

        Member1 member1= orderMapper.selectByCondition(dto.getTelephone());
       // 4、检查当前用户是否为会员(以手机号来确定用户的唯一性)，如果是会员则直接完成预约，如果不是会员则自动完成注/ 册并进行预约
        Member1 mm = null;
        if (member1==null){
            mm =  BeanUtil.copyProperties(dto,Member1.class);
            member1.setRegTime(LocalDate.now().atStartOfDay());
            orderMapper.addMember(mm);

        }else {
            mm=member1;
        }
        Order order =orderMapper.selectByCondition(mm.getId(),dto.getSetmealId(),dto.getOrderDate());
        if (order!=null){
            throw new RuntimeException("您已经预约过了，无需再次预约");
        }
        //保存到order表返回id

        Order od=new Order();
        od.setSetmealId(dto.getSetmealId());
        od.setMemberId(mm.getId());
        od.setOrderDate(dto.getOrderDate());

        od.setOrderType("微信预约");
        od.setOrderStatus("已到诊");
        orderMapper.add(od);


        //5、预约成功，更新当日的已预约人数
        orderSetting.setReservations(orderSetting.getReservations()+1);
        orderMapper.updateByOrderDate(orderSetting);
        return od.getId();

    }

    @Override
    public OrderVo findById(Integer id) {
        OrderVo orderVo = orderMapper.findById(id);
        return orderVo;
    }
}
